package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MybatisPlus的service层自动实现
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;
    /**
     *根据id查询分类的实现
     * @param id 分类id
     * @return
     */
    @Override
    public CategoryDTO findById(Long id) {
        return new CategoryDTO(this.getById(id));
    }


    /**
     *根据id集合查询分类集合的实现
     * @param ids id集合
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }

    /**
     * 根据父类目录id查询子分类的业务实现
     * @param pid 父目录id
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByParentId(Long pid) {
        return CategoryDTO.convertEntityList(this.query().eq("parent_id",pid).list());
    }

    /**
     * 根据品牌id查询分类集合的业务层实现
     * @param id 品牌id
     * @return
     */
    @Override
    public List<CategoryDTO> queryBrandById(Long id) {
        //根据品牌id查询中间表，得到中间表集合
        List<CategoryBrand> brandList = categoryBrandService.query().eq("brand_id", id).list();
        //判断中间表是否为空
        if(CollectionUtils.isEmpty(brandList)){
            return Collections.emptyList();
        }
        //根据中间表查询分类集合
        List<Long> longList = brandList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());
        List<Category> categoryList = listByIds(longList);
        return CategoryDTO.convertEntityList(categoryList);
    }
}
